<template>
  <div class="body">
    <myHeader></myHeader>
    <div class="content-body" v-if="listData[pageIndex]">
      <div class="left fl">
        <div class="kt pos">
          <div class="tit">技考邦</div>
          第01考台
        </div>
        <div class="user-info pos">
          <div class="tit" style="left: 38px;">考生信息</div>
          <img :src="user.profilesPic || '@/assets/img/initAvatar.jpg'" alt="">
          <p><label for="" class="mr">姓</label> <label for="">名：</label> <span>{{ user.nickName }}</span></p>
          <p><label for="">考试类型：</label> <span>{{ navData[navIndex].name }}</span></p>
          <p><label for="">考试科目：</label> <span>{{ navData[navIndex].children[navInd].name }}</span></p>
        </div>
        <div class="waste-time pos">
          <div class="tit" style="left: 38px;">剩余时间</div>
          <span class="countdown">
            <el-countdown :value="downTime" @finish="finishFn" />
          </span>
        </div>
      </div>
      <div class="center fl">
        <div class="kstm pos">
          <div class="tit">考试题目</div>
          <p class="name">({{ listData[pageIndex].typeName }}){{ pageIndex + 1 }}、{{ listData[pageIndex].question }}</p>
          <div class="option">
            <p v-for="(item, index) in listData[pageIndex].options" :key="index">{{ item.letter }}：<span
                v-html="item.title"></span></p>
          </div>
          <div class="tm-answer">
            <div class="fl sec-aswer">您的选项是：{{ listData[pageIndex].answer }}</div>
            <div class="fr aswer"><span class="fl">请选择：</span>
              <template v-if="listData[pageIndex].type === 0 || listData[pageIndex].type === 2">
                <li class="danxuan" v-for="(item, index) in listData[pageIndex].options" :key="index"
                  :class="item.letter === listData[pageIndex].answer ? 'active' : ''" @click="optionsChangeFn(item)">{{
                    item.letter }}</li>
              </template>
              <template v-else>
                <li class="danxuan" v-for="(item, index) in listData[pageIndex].options" :key="index"
                  :class="item.checked ? 'active' : ''" @click="optionsChangeFn(item)">{{ item.letter }}</li>
              </template>
            </div>
          </div>
        </div>
        <div class="tsxx pos fl">
          <div class="tit">提示信息</div>
          <span class="tsxxt" v-show="listData[pageIndex].type === 0">单选题,请在备选答案中选择你认为正确的答案！</span>
          <span class="tsxxt" v-show="listData[pageIndex].type === 1">多选题,请在备选答案中选择你认为正确的答案！</span>
          <span class="tsxxt" v-show="listData[pageIndex].type === 2">判断题，请判断对错！</span>
        </div>
        <div class="btn-wrap fl">
          <a href="javascript:;" class="btn pre" @click="pageChangeFn('prev')">上一题</a>
          <a href="javascript:;" class="btn next" @click="pageChangeFn('next')">下一题</a>
          <a href="javascript:;" class="btn jj" @click="submitFn">交卷</a>
        </div>
      </div>
      <div class="right fl">
        <div class="Qn-wrap">
          <li v-for="(item, index) in listData" :key="index" class="qn"
            :class="[index === pageIndex ? 'active' : '', item.answer ? 'selected' : 'noSel']"
            @click="pageIndex = index">
            <p>{{ index + 1 }}</p>
            <p class="rightA" v-show="item.answer && item.answer === item.correctAnswer">{{ item.answer }}</p>
            <p class="wrong" v-show="item.answer && item.answer !== item.correctAnswer">{{ item.answer }}</p>
          </li>
        </div>
      </div>
      <div class="q-detail pos fl" v-show="listData[pageIndex].imgs">
        <div class="tit">图片信息</div>
        <el-image class="q-img" v-for="(item, index) in listData[pageIndex].imgs" :key="index" :src="item" alt=""
          :preview-src-list="[item]" preview-teleported :initial-index="index" />
      </div>
    </div>
    <!-- 自动结束考试 -->
    <el-dialog v-model="examEndVisible" title="系统提示" width="420" :close-on-click-modal="false" :close-on-press-escape="false" :show-close="false" align-center>
      <span>{{ examEndTitle }}</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="examEndFn">关闭（{{ closeTime }}s）</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import myHeader from '@/components/header.component.vue';
import { useNavStore } from '@/stores/nav.store.js';
import { ElMessage, ElMessageBox } from 'element-plus';
import { ref, getCurrentInstance, onUnmounted, onMounted } from 'vue';
const user = ref(localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : {})
const navStore = useNavStore()
const navData = ref(navStore.listData || [])
const navIndex = ref(0)
const navInd = ref(0)
const { $api } = getCurrentInstance().appContext.config.globalProperties;
import { useRoute, useRouter } from 'vue-router';
const route = useRoute()
const router = useRouter()
const pageData = ref([])
const pageIndex = ref(0)
const listData = ref([])
const total = ref(0)
const id = ref(null)
const downTime = ref(0)
const examSetting = ref({})
const deductPoints = ref(0)
const examEndVisible = ref(false)
const examEndInterval = ref()
const examEndTitle = ref('考试时间结束，试卷已提交')
const examEndId = ref(null)
const closeTime = ref(0)

// 判断是否登录
if (!localStorage.getItem('token')) {
  router.replace('/login')
}
// 倒计时
if (localStorage.getItem('examSetting')) {
  examSetting.value = JSON.parse(localStorage.getItem('examSetting'))
  downTime.value = Date.now() + (examSetting.value.duration * 1000);
}
// 设置导航下标
const setNavIndexIndFn = () => {
  navData.value.forEach((item, index) => {
    if (item.url === route.params.type) {
      navIndex.value = index;
    }
    if (route.params.subject) {
      item.children.forEach((ite, ind) => {
        if (ite.id === Number(route.params.subject)) {
          navInd.value = ind;
        }
      })
    }
  })
}
setNavIndexIndFn()
// 获取考试习题
const getListFn = () => {
  $api.getSimulationExerciseApi({
    subjectId: route.params.subject
  }).then((res) => {
    if (res.errno === 0) {
      if (res.result) {
        id.value = res.result.id;
        localStorage.setItem('isRefresh', res.result.id)
        // 追加类型名称
        res.result.exerciseList.forEach(item => {
          item.typeName = item.type === 0 ? '单选题' : item.type === 1 ? '多选题' : '判断题';
          item.options.filter(x => x.checked = false)
        })
        pageData.value = res.result.exerciseInfos;
        listData.value = res.result.exerciseList;
        total.value = res.result.exerciseList.length;
        return false;
      }
      ElMessage.warning('未发现可做习题')
      return false;
    }
    ElMessage.error(res.errmsg)
  })
}
getListFn()
// 上一题 下一题
const pageChangeFn = (val) => {
  if (val === 'prev') {
    if (pageIndex.value < 1) {
      ElMessageBox.confirm('已经是第一题了', '系统提示', {
        showClose: false,
        showCancelButton: false,
        confirmButtonText: '我已知晓'
      }).catch((err) => { })
      return false;
    }
    pageIndex.value--;
  }
  if (val === 'next') {
    let currentData = listData.value[pageIndex.value];
    if (pageIndex.value + 1 >= total.value) {
      ElMessageBox.confirm('已经是最后一题了', '系统提示', {
        showClose: false,
        showCancelButton: false,
        confirmButtonText: '我已知晓'
      }).catch((err) => { })
    }
    // 多选题下一题记录用户选择
    if (currentData.type === 1) {
      let _answer = currentData.options.filter(x => x.checked).map(x => x.letter).join('')
      currentData.answer = _answer;
      // 记录多选题扣分情况
      if (_answer !== currentData.correctAnswer) {
        deductPoints.value += examSetting.value.checkboxScore;
      }
      // 及格分大于你的扣分情况弹窗提示
      let _passScore = examSetting.value.fullScore - deductPoints.value;
      if (_answer !== currentData.correctAnswer && examSetting.value.passScore > _passScore) {
        ElMessageBox.confirm('您的本次考试不合格，是否继续答题？', '系统提示', {
          showClose: false,
          cancelButtonText: '继续答题',
          confirmButtonText: '确认交卷',
          closeOnClickModal: false,
          closeOnPressEscape: false,
          closeOnHashChange: false
        }).then(() => {
          submitExamFn()
        }).catch(() => { })
      }
    }
    if (pageIndex.value + 1 < total.value) {
      pageIndex.value++;
    }
  }
}
// 请选择
const optionsChangeFn = (val) => {
  let currentData = listData.value[pageIndex.value];
  if (!currentData.answer) {
    // 单选 判断
    if (currentData.type === 0 || currentData.type === 2) {
      currentData.answer = val.letter;
      // 分别记录单选和判断扣分情况
      if (val.letter !== currentData.correctAnswer) {
        if (currentData.type === 0) {
          deductPoints.value += examSetting.value.radioScore;
        }
        if (currentData.type === 2) {
          deductPoints.value += examSetting.value.judgeScore;
        }
      }
      // 及格分大于你的扣分情况弹窗提示
      let _passScore = examSetting.value.fullScore - deductPoints.value;
      if (val.letter !== currentData.correctAnswer && examSetting.value.passScore > _passScore) {
        ElMessageBox.confirm('您的本次考试不合格，是否继续答题？', '系统提示', {
          showClose: false,
          cancelButtonText: '继续答题',
          confirmButtonText: '确认交卷',
          closeOnClickModal: false,
          closeOnPressEscape: false,
          closeOnHashChange: false
        }).then(() => {
          submitExamFn()
        }).catch(() => { })
      }
      if (pageIndex.value + 1 < total.value) {
        setTimeout(() => {
          pageIndex.value++;
        }, 300)
      }
    }
    // 多选题
    else {
      val.checked = !val.checked;
    }
  }
}
// 倒计时结束
const finishFn = () => {
  closeTime.value = 3;
  submitExamFn(false)
  popupFn()
}
// 弹窗计时器
const popupFn = () => {
  examEndVisible.value = true;
  examEndInterval.value = setInterval(() => {
    closeTime.value--;
    if (closeTime.value < 1) {
      clearInterval(examEndInterval.value)
      examEndVisible.value = false;
      router.replace(`/${route.params.type}/${route.params.subject}/result/${examEndId.value}`)
    }
  }, 1000)
}
// 关闭
const examEndFn = () => {
  examEndVisible.value = false;
  clearInterval(examEndInterval.value)
  router.replace(`/${route.params.type}/${route.params.subject}/result/${examEndId.value}`)
}
// 交卷
const submitFn = () => {
  ElMessageBox.confirm('<p>1、点击【确认交卷】，将提交考试成绩，结束考试。</p><p>2、点击【继续答题】，将继续答题,倒计时结束无法继续答题。</p>', '系统提示', {
    showClose: false,
    cancelButtonText: '继续答题',
    confirmButtonText: '确认交卷',
    dangerouslyUseHTMLString: true
  }).then(() => {
    submitExamFn()
  }).catch(() => { })
}
// 确认交卷
const submitExamFn = (isJump = true) => {
  let _exerciseInfos = []
  if (listData.value && listData.value.length > 0) {
    _exerciseInfos = listData.value.map(x => { return { id: x.id, answer: x.answer } })
  }
  $api.submitResultApi({
    id: id.value || localStorage.getItem('isRefresh'),
    exerciseInfos: _exerciseInfos
  }).then((res) => {
    if (res.errno === 0) {
      examEndId.value = res.result.id;
      // 获取排名
      $api.getRankApi({
        rankWeight: res.result.rankWeight
      }).then((res) => {
        if (res.errno === 0) {
          if (isJump) {
            router.replace(`/${route.params.type}/${route.params.subject}/result/${examEndId.value}`)
          }
          return false;
        }
        ElMessage.error(res.errmsg)
      })
      return false;
    }
    ElMessage.error(res.errmsg)
  })
}
// 页面加载后
onMounted(() => {
  // 判断页面是否存在刷新操作
  if (localStorage.getItem('isRefresh')) {
    submitExamFn(false)
    router.back()
  }
})
// 页面销毁
onUnmounted(() => {
  clearInterval(examEndInterval.value)
})
</script>

<style lang="scss" scoped>
@import '../assets/css/m-down.css';
@import '../assets/css/m-index.css';
@import '../assets/css/mnks.css';

.body {
  min-height: 100vh;
  background: #FFF;
}
</style>
<style>
.waste-time .el-statistic__content {
  color: #FF9001;
}
</style>